package com.fc.service.impl;

import org.hibernate.Criteria
import org.hibernate.criterion.Restrictions
import org.springframework.stereotype.Repository
import org.springframework.transaction.annotation.Transactional

import com.fc.entities.FoodJournal
import com.fc.entities.User
import com.fc.service.FoodJournalService

/**
 * 
 * @author Ács Ádám
 *
 */
@Repository("foodJournalService")
@Transactional
class FoodJournalServiceImpl extends BaseServiceImpl<FoodJournal> implements FoodJournalService{
	@Override
	List<FoodJournal> findAllByDate(Date date) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		c.add(Calendar.DATE, 1);
		Date nextDay = c.getTime();
		
		Criteria criteria = currentSession().createCriteria(FoodJournal.class);
		criteria.add(Restrictions.between('date', date, nextDay));
		List<FoodJournal> list = criteria.list();

		return list;
	}
	
	@Override
	public int getSumCalorie(Date date) {
		def entries = findAllByDate(date)
		Integer sum = entries.sum() {
			it.recipe.getSumCalorie()
		}
		return sum?:0
	}

	@Override
	public int getSumProtein(Date date) {
		def entries = findAllByDate(date)
		Integer sum = entries.sum() {
			it.recipe.getSumProtein()
		}
		return sum?:0
	}

	@Override
	public int getSumCarbohydrate(Date date) {
		def entries = findAllByDate(date)
		Integer sum = entries.sum() {
			it.recipe.getSumCarbohydrate()
		}
		return sum?:0
	}

	@Override
	public int getSumFat(Date date) {
		def entries = findAllByDate(date)
		Integer sum = entries.sum() {
			it.recipe.getSumFat()
		}
		return sum?:0
	}

	@Override
	public int getSumFiber(Date date) {
		def entries = findAllByDate(date)
		Integer sum = entries.sum() {
			it.recipe.getSumFiber()
		}
		return sum?:0
	}

	@Override
	public List<FoodJournal> findAll() {
		findAll(FoodJournal.class)
	}

	@Override
	public List<FoodJournal> findAllByUser(User user) {
		Criteria criteria = currentSession().createCriteria(FoodJournal.class)
		return criteria.add(Restrictions.eq("user", user)).list()
	}
}
